//
//  LBXHttpServer.m
//  WebServerTools
//
//  Created by 夏利兵 on 2020/10/19.
//  Copyright © 2020 com.lbx. All rights reserved.
//

#import "LBXHttpMockServer.h"
#import <ifaddrs.h>
#import <arpa/inet.h>
#import <GCDWebServer/GCDWebServer.h>
#import <GCDWebServerStreamedResponse.h>
#import <GCDWebServerDataResponse.h>
#import <GCDWebServerDataRequest.h>

@interface LBXHttpMockServer()
@property (nonatomic, strong) GCDWebServer* httpServer;
@property (nonatomic, strong) NSArray<NSDictionary*> *echoList;
@property (nonatomic, assign) NSInteger port;
@end

@implementation LBXHttpMockServer


- (BOOL)start{
    
    GCDWebServer* webServer = [[GCDWebServer alloc] init];
    
    self.httpServer = webServer;
    
    __weak typeof(self) weakSelf = self;
        
    [webServer addHandlerForMethod:@"GET" path:@"/request" requestClass:[GCDWebServerRequest class] processBlock:^GCDWebServerResponse * _Nullable(__kindof GCDWebServerRequest * _Nonnull request) {
        
        //http://192.168.0.107:8080/getDetail?id=id1234567&val=222
        
        //        request.query 为url上的参数，不是http body，所有只有get方法  request.query才有可能有参数
        NSLog(@"headers:%@",request.headers);
        
        //获取对应请求的预设返回
        NSDictionary *responseJson = nil;
        if (weakSelf.echoList) {
            for (NSDictionary *dic in weakSelf.echoList) {
                if ([dic[@"request"] isEqual:request.query] ) {
                    responseJson = dic[@"response"];
                }
            }
        }
        
        //没有预设，直接echo返回，加一个echo字段
        if (!responseJson) {
            
            NSMutableDictionary *responseJMutableJson = [NSMutableDictionary dictionaryWithDictionary:request.query];
            [responseJMutableJson setValue:@"echo" forKey:@"serverecho"];
            responseJson = responseJMutableJson;
        }
        
        GCDWebServerDataResponse* response = [GCDWebServerDataResponse responseWithJSONObject:responseJson];
        
        
        dispatch_async(dispatch_get_main_queue(), ^{
            // 更新界面
            //        weakSelf.httprequestLog.stringValue = [NSString stringWithFormat:@"Get Method paras:%@",request.query];
        });
        return response;
    }];
    
    [webServer addHandlerForMethod:@"POST" path:@"/request" requestClass:[GCDWebServerDataRequest class] processBlock:^GCDWebServerResponse * _Nullable(__kindof GCDWebServerDataRequest * _Nonnull request) {
        
        NSLog(@"headers:%@",request.headers);
        
        NSDictionary *requestJson  = [self returnDictionaryWithDataPath:request.data];
        
        //获取对应请求的预设返回
        NSDictionary *responseJson = nil;
        if (weakSelf.echoList) {
            for (NSDictionary *dic in weakSelf.echoList) {
                if ([dic[@"request"] isEqual:requestJson] ) {
                    responseJson = dic[@"response"];
                }
            }
        }
        
        //没有预设，直接echo返回，加一个echo字段
        if (!responseJson) {
            
            NSMutableDictionary *responseJMutableJson = [NSMutableDictionary dictionaryWithDictionary:requestJson];
            [responseJMutableJson setValue:@"echo" forKey:@"macserverecho"];
            responseJson = responseJMutableJson;
        }
        
        GCDWebServerDataResponse* response = [GCDWebServerDataResponse responseWithJSONObject:responseJson];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
//            weakSelf.httprequestLog.stringValue = [NSString stringWithFormat:@"Post Method paras:%@",requestJson];
        });
        
        return response;
    }];
    
    [webServer addHandlerForMethod:@"POST" path:@"/request" requestClass:[GCDWebServerDataRequest class] processBlock:^GCDWebServerResponse * _Nullable(__kindof GCDWebServerDataRequest * _Nonnull request) {
        
        NSDictionary *requestJson  = [self returnDictionaryWithDataPath:request.data];
        
        //获取对应请求的预设返回
        NSDictionary *responseJson = nil;
        if (weakSelf.echoList) {
            for (NSDictionary *dic in weakSelf.echoList) {
                if ([dic[@"request"] isEqual:requestJson] ) {
                    responseJson = dic[@"response"];
                }
            }
        }
        
        //没有预设，直接echo返回，加一个echo字段
        if (!responseJson) {
            
            NSMutableDictionary *responseJMutableJson = [NSMutableDictionary dictionaryWithDictionary:requestJson];
            [responseJMutableJson setValue:@"echo" forKey:@"macserverecho"];
            responseJson = responseJMutableJson;
        }
        
        GCDWebServerDataResponse* response = [GCDWebServerDataResponse responseWithJSONObject:responseJson];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
//            weakSelf.httprequestLog.stringValue = [NSString stringWithFormat:@"Post Method paras:%@",requestJson];
        });
        
        return response;
    }];
    

//
//    self.webStaticServerUrl = [NSString stringWithFormat:@"http://%@:%lu/request",[self deviceAdress],(unsigned long)port];
//    self.showIpLabel.stringValue = [NSString stringWithFormat:@"%@",self.webStaticServerUrl];
//
    //卡住主线程，适用在 main 控制台应用程序使用
    //    [webServer runWithPort:port bonjourName:@"test"];
    
    
    if( ![webServer startWithPort:_port bonjourName:@"test"] )
    {
//        self.showIpLabel.stringValue = [NSString stringWithFormat:@"启动失败 端口号：%lu (注意是不是端口被占用了)",(unsigned long)port];
        self.httpServer = nil;
        return NO;
    }
    else
    {
//        NSPasteboard *pasteboard = [NSPasteboard generalPasteboard];
//
//        [pasteboard declareTypes:@[NSPasteboardTypeString] owner:nil];
//
//        if ([pasteboard setString:self.webStaticServerUrl forType:NSPasteboardTypeString])
//        {
//            NSLog(@"success");
//        }
    }
    
    return YES;
}

- (NSDictionary*)returnDictionaryWithDataPath:(NSData*)data
{
    if (!data) {
        return @{};
    }
    
    NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
    
    if (!jsonDict) {
        //id=1&pwd=val1 形式字符串
        NSString *receiveStr = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
        jsonDict = [self dicByURLParameters:receiveStr];
    }
    
    return jsonDict;
}

#pragma mark - 解析url中的参数，生成NSMutableDictionary

- (NSDictionary *)dicByURLParameters:(NSString *)urlPara {
    
    // 以字典形式将参数返回
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    
    // 判断参数是单个参数还是多个参数
    if ([urlPara containsString:@"&"]) {
        
        // 多个参数，分割参数
        NSArray *urlComponents = [urlPara componentsSeparatedByString:@"&"];
        
        for (NSString *keyValuePair in urlComponents) {
            // 生成Key/Value
            NSArray *pairComponents = [keyValuePair componentsSeparatedByString:@"="];
            NSString *key = [pairComponents.firstObject stringByRemovingPercentEncoding];
            NSString *value = [pairComponents.lastObject stringByRemovingPercentEncoding];
            
            // Key不能为nil
            if (key == nil || value == nil) {
                continue;
            }
            
            id existValue = [params valueForKey:key];
            
            if (existValue != nil) {
                
                // 已存在的值，生成数组
                if ([existValue isKindOfClass:[NSArray class]]) {
                    // 已存在的值生成数组
                    NSMutableArray *items = [NSMutableArray arrayWithArray:existValue];
                    [items addObject:value];
                    
                    [params setValue:items forKey:key];
                } else {
                    
                    // 非数组
                    [params setValue:@[existValue, value] forKey:key];
                }
                
            } else {
                
                // 设置值
                [params setValue:value forKey:key];
            }
        }
    } else {
        // 单个参数
        
        // 生成Key/Value
        NSArray *pairComponents = [urlPara componentsSeparatedByString:@"="];
        
        // 只有一个参数，没有值
        if (pairComponents.count == 1) {
            return nil;
        }
        
        // 分隔值
        NSString *key = [pairComponents.firstObject stringByRemovingPercentEncoding];
        NSString *value = [pairComponents.lastObject stringByRemovingPercentEncoding];
        
        // Key不能为nil
        if (key == nil || value == nil) {
            return nil;
        }
        
        // 设置值
        [params setValue:value forKey:key];
    }
    
    return params;
}




- (NSString *)deviceIPAdress {
    
    NSString *address = @"";
    
    struct ifaddrs *interfaces = NULL;
    
    struct ifaddrs *temp_addr = NULL;
    
    int success = 0;
    
    success = getifaddrs(&interfaces);
    
    if (success == 0) { // 0 表示获取成功
        
        temp_addr = interfaces;
        
        while (temp_addr != NULL) {
            
            if( temp_addr->ifa_addr->sa_family == AF_INET) {
                
                // Check if interface is en0 which is the wifi connection on the iPhone
                //                NSLog(@"%@",[NSString stringWithUTF8String:temp_addr->ifa_name]);
                //                 NSString* str = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)];
                //                NSLog(@"%@",str);
                
                if ([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"en0"] || [[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"en1"] ) {
                    
                    // Get NSString from C String
                    address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)];
                    
                }
            }
            
            temp_addr = temp_addr->ifa_next;
        }
    }
    
    freeifaddrs(interfaces);
    
    return address;
    
}

@end
